﻿using System;
using Silver3D.Math;

namespace Silver3D.Graphics
{
    /// <summary>
    /// Represents a generic Matrix44 transformation.
    /// </summary>
    public class MatrixTransform : Transform
    {
        /// <summary>
        /// Used by derived classes to request a matrix representation update.
        /// </summary>
        protected bool IsDirty { get; set; }

        /// <summary>
        /// Updated by derived classes and used as a performance improvement.
        /// </summary>
        protected Matrix44 CachedMatrix { get; set; }

        /// <summary>
        /// Gets or sets the matrix that is used by this transformation.
        /// </summary>
        public Matrix44 Matrix
        {
            get
            {
                if (IsDirty) UpdateMatrix();
                return CachedMatrix;
            }
            set
            {
                CachedMatrix = value;
                IsDirty = false;
            }
        }

        /// <summary>
        /// Returns the matrix representation of this Transform.
        /// </summary>
        /// <returns>A Matrix44.</returns>
        public override Matrix44 ToMatrix()
        {
            return Matrix;
        }

        public MatrixTransform(Scene scene, string id)
            : this(scene, id, null, Matrix44.Identity)
        {
        }

        public MatrixTransform(Scene scene, string id, Node parent)
            : this(scene, id, parent, Matrix44.Identity)
        {
        }

        public MatrixTransform(Scene scene, string id, Node parent, Matrix44 matrix)
            : base(scene, id)
        {
            Matrix = matrix;
        }

        protected virtual void UpdateMatrix() { }
    }
}
